package com.hfplm.lhh.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;

import com.teamcenter.rac.aif.AbstractAIFUIApplication;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentBOMWindow;
import com.teamcenter.rac.kernel.TCComponentBOMWindowType;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentRevisionRule;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;

public class BOMLinePropertyHandler extends AbstractHandler {
	private TCSession session;
	private AbstractAIFUIApplication app;
	InterfaceAIFComponent target;
	@Override
	public Object execute(ExecutionEvent arg0) throws ExecutionException {
		app = AIFUtility.getCurrentApplication();
		session = (TCSession)app.getSession();
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				target = app.getTargetComponent();
				
				System.out.println(target.getClass());
				System.out.println(target.getType());
				if(!(target instanceof TCComponentItemRevision)) {
					return;
				}
				TCComponentItemRevision revision = (TCComponentItemRevision) target;
				try {
					TCComponentBOMWindow window = createBOMWindow(null);
					TCComponentBOMLine newRootLine = window.setWindowTopLine(revision.getItem(), revision, null,null);
					AIFComponentContext [] contexts = newRootLine.getChildren();
					for (AIFComponentContext aifComponentContext : contexts) {
						TCComponentBOMLine bomLine = (TCComponentBOMLine)aifComponentContext.getComponent();
						System.out.println(bomLine.getProperty("bl_ref_designator"));
						bomLine.setProperty("bl_ref_designator", "d001");
						bomLine.save();
					}
					
				} catch (TCException e) {
					e.printStackTrace();
				}
			

			}
			
		};
		new Thread(runnable).start();
		return null;
	}
	
	public TCComponentBOMWindow createBOMWindow(TCComponentRevisionRule revRule)
			throws TCException {
		TCComponentBOMWindowType bomWinType = (TCComponentBOMWindowType) session.getTypeComponent("BOMWindow");
		TCComponentBOMWindow bomWin = bomWinType.create(revRule);
		return bomWin;
	}
}
